﻿using System.Diagnostics;
using InSimDotNet;
using InSimDotNet.Packets;
using LFSRecord2.Events;
using LFSRecord2.Misc;

namespace LFSRecord2.Model
{
    public class LfsState
    {
        public bool HasSynced = false;
        public string CurrentReplayName { get; set; }

        public float ReplaySpeed { get; set; }	// 4-byte float - 1.0 is normal speed

        public StateFlags Flags { get; set; }			// ISS state flags (see below)
        public ViewIndentifier InGameCam { get; set; }		// Which type of camera is selected (see below)
        public int ViewPLID { get; set; }		// Unique ID of viewed player (0 = none)

        public int NumP { get; set; }			// Number of players in race
        public int NumConns { get; set; }		// Number of connections including host
        public int NumFinished { get; set; }	// Number finished or qualified
        public int RaceInProg { get; set; }		// 0 - no race / 1 - race / 2 - qualifying

        public int QualMins { get; set; }
        public int RaceLaps { get; set; }		// see "RaceLaps" near the top of this document

        public string Track { get; set; }  		// short name for track e.g. FE2R
        public int Weather { get; set; }		// 0,1,2...
        public int Wind { get; set; }			// 0=off 1=weak 2=strong

        public string HName { get; set; }          // Hostname in case of multiplayer mode

        public bool ShiftUInternal { get; set; }  // Here we store what the view mode of LFS _should_ be, not what it is.

        public int InSimVersion { get; private set; }     // InSim version as reported by InSim

        public LfsState()
        {
            CurrentReplayName = "";
            ShiftUInternal = true;
        }

        public void InSimVer(InSim insim, IS_VER ver)
        {
            InSimVersion = ver.InSimVer;
        }

        public void StateInfo(InSim insim, IS_STA sta)
        {
            Debug.WriteLine("STA.Flags : " + sta.Flags);
            bool trackChanged = (Track == sta.Track) ? false : true;
            //Debug.WriteLine(Track + " - " + sta.Track);

            ReplaySpeed = sta.ReplaySpeed;
            Flags = sta.Flags;
            InGameCam = sta.InGameCam;
            ViewPLID = sta.ViewPLID;
            NumP = sta.NumP;
            NumConns = sta.NumConns;
            NumFinished = sta.NumFinished;
            RaceInProg = sta.RaceInProg;
            QualMins = sta.QualMins;
            RaceLaps = sta.RaceLaps;
            Track = sta.Track;
            Weather = sta.Weather;
            Wind = sta.Wind;

            string longTrack = LfsHelper.ShortToLongTrack(Track);

            if (longTrack.Length > 0 && trackChanged)
                ServicesFactory.EventService.GetEvent<TrackChangedEvent>().Publish(longTrack);
        }

        public void InSimMulti(InSim insim, IS_ISM ism)
        {
            HName = ism.HName;
        }
    }
}
